import paho.mqtt.client as mqtt
import wol
import socket
import os
import platform
# 连接到 MQTT 服务器
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker")
        client.subscribe("computer1006")  # 订阅主题
        client.subscribe("computer2006")
    else:
        print(f"Connection failed with code {rc}")


# 处理接收到的消息
def on_message(client, userdata, msg):
    if msg.topic == "computer1006":
        string = msg.payload.decode('utf-8')
        if string == "on":
            wol.wakeup("00-D8-61-52-F4-F8")
        if string == "off":
            ipaddress = get_local_ip()
            if ipaddress=="192.168.3.9":
                shutdown_computer()

    if msg.topic == "computer2006":
        wol.wakeup("00-E2-69-67-A3-C6")
    print(f"Received message '{msg.payload.decode()}' on topic '{msg.topic}'")

def get_local_ip():
    try:
        # 创建一个 UDP socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 连接到一个公共的 DNS 服务器
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

def shutdown_computer():
    system = platform.system().lower()

    if system == "windows":
        os.system("shutdown /s /t 1")
    elif system == "linux" or system == "darwin":  # Darwin is macOS
        os.system("sudo shutdown -h now")
    else:
        print(f"Unsupported operating system: {system}")

# 创建 MQTT 客户端
client = mqtt.Client(client_id="05dcaf54da4043b69007036b866e5500")

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到 MQTT 服务器
client.connect("bemfa.com", 9501, 60)  # 替换为您自己的 MQTT 服务器地址和端口
